package com.fan.chat.component;

import com.plexpt.chatgpt.ChatGPTStream;
import com.plexpt.chatgpt.util.Proxys;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.net.Proxy;

@Slf4j
@Component
public class ChatGPTStreamComponent {

    @Autowired
    private ChatConfig config;

    public ChatGPTStream getChatGPTStream() {
        ChatGPTStream chatGPTStream = getInitialChatGPTStream();
        chatGPTStream.setApiKeyList(config.getApiKey());
        return chatGPTStream.init();
    }

    public ChatGPTStream getChatGPTStream(String apiKey) {
        ChatGPTStream chatGPTStream = getInitialChatGPTStream();
        chatGPTStream.setApiKey(apiKey);
        return chatGPTStream.init();
    }

    public ChatGPTStream getFasterChatGPTStream() {
        ChatGPTStream fasterChatGPTStream = getInitialChatGPTStream();
        fasterChatGPTStream.setApiKeyList(config.getFasterApiKey());
        return fasterChatGPTStream.init();
    }

    private ChatGPTStream getInitialChatGPTStream() {
        ChatGPTStream chatGPTStream = ChatGPTStream.builder()
                .timeout(600)
                .apiHost(config.apiHost)
                .build();

        String proxyAddress = config.getProxyAddress();
        if (StringUtils.hasLength(proxyAddress)) {
            try {
                String address = proxyAddress;
                int port = 80;
                int lastIndex = proxyAddress.lastIndexOf(":");
                if (lastIndex > 0) {
                    address = proxyAddress.substring(0, lastIndex);
                    port = Integer.parseInt(proxyAddress.substring(lastIndex + 1));
                }
                log.info("proxy address: {}, port: {}", address, port);
                Proxy proxy = Proxys.http(address, port);
                chatGPTStream.setProxy(proxy);
            } catch (Exception e) {
                log.warn("proxy create fail: ", e);
            }
        }
        return chatGPTStream;
    }

}
